<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/18
 * Time: 17:56
 */

namespace App\Game\Traits;


trait PbTrait
{
    private function generateToken($agentCode, $agentKey, $secretKey)
    {
        $timestamp = time() * 1000;
        $hashToken = md5($agentCode . $timestamp . $agentKey);
        $tokenPayLoad = $agentCode . '|' . $timestamp . '|' . $hashToken;
        $token = $this->encryptAES($secretKey, $tokenPayLoad);

        return $token;
    }

    private function encryptAES($secretKey, $tokenPayLoad)
    {
        $iv = "RandomInitVector";
        $encrypt = openssl_encrypt($tokenPayLoad, "AES-128-CBC", $secretKey, OPENSSL_RAW_DATA, $iv);

        return base64_encode($encrypt);
    }

    private function pbRequest($method='POST',$url,array $params)
    {
        $headers=[
          'userCode'=>$this->agentCode,
          'token'=>$this->generateToken($this->agentCode,$this->agentKey,$this->secretKey)
        ];

        $response=$this->request($method,$this->gameUrl.$url,$params,$headers);

        return json_decode($response,true);
    }


    /**
     * gameapi
     * 2018/9/24 17:35
     * Administrator
     * apiDataParse
     * 字段解析
     * @param array $apiData
     * @param array $data
     * @return array
     */
    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->statusParse($apiData, $data);
        return $data;
    }

    /**
     * gameapi
     * 2018/9/24 17:36
     * Administrator
     * statusParse
     * 解析状态字段
     * @param array $apiData
     * @param array $data
     * @return array
     */
    private function statusParse(array $apiData, array $data)
    {
        if (array_key_exists('status', $apiData)) {
            switch ($apiData['status']) {
                case 'SETTLED':
                    $data['status'] = 1;
                    break;
                case 'CANCELLED':
                    $data['status'] = -1;
                    break;
                case 'DELETED':
                    $data['status'] = -1;
                    break;
                case 'OPEN':
                    $data['status'] = 0;
                    break;
                case 'PENDING':
                    $data['status'] = 0;
                    break;
                default:
                    $data['status'] = 1;
                    break;
            }
        }

        return $data;
    }

}